package com.dapeis.web.wx.controller.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ag.core.exception.InvalidParamException;
import com.ag.core.exception.SysTipsException;
import com.ag.module.common.api.domain.SMS;
import com.ag.module.common.api.service.SMSService;
import com.ag.module.common.api.service.text.base.DicText;
import com.ag.utils.NumberUtils;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.exception.SMSSendFaildException;
import com.dapeis.tx.sms.SMSNoticeText;
import com.dapeis.web.wx.controller.ISMSController;
import com.dapeis.web.wx.controller.RestController;
import com.google.gson.JsonElement;

/**
 * @author 作者 E-mail:
 * @version 创建时间：2017年5月4日 下午6:22:43 类说明
 */
@Controller
@RequestMapping("/wx/sms")
public class SMSImpController extends RestController implements ISMSController {

    @Resource
    SMSService smsService;

    @Override

    public JsonElement send(@PathVariable String channel, @RequestParam String contact,
	    HttpServletRequest request) {

	if (StringUtils.isBlank(channel) || StringUtils.isBlank(contact)) {
	    throw new InvalidParamException();
	}
	if (!contact.matches(StylistConstants.mobilePhonePattern.pattern())
		|| contact.length() != 11) {
	    throw new InvalidParamException("手机号码格式不正确");
	}

	String verifyCode = String.valueOf(NumberUtils.random(4));
	int channelType = -1;
	DicText nt = null;
	if ("bind".equals(channel)) {
	    channelType = StylistConstants.ChannelType.USER.WECHAT_BING;
	    nt = new SMSNoticeText(verifyCode);
	    SMS unExpireationTimeSMS = smsService.getUnExpireationTimeSMS(
		    channelType, contact);
	    if (unExpireationTimeSMS != null) {// 如果有,
		smsService.getDefaultSMSSendChannel().sendSMS(contact,
			unExpireationTimeSMS.getContent());
	    } else {
		boolean flag = smsService.sendSMS(channelType, contact,
			verifyCode, nt.content());
		if (!flag) {
		    throw new SMSSendFaildException();
		}
	    }
	    return success();
	} else {
	    throw new SysTipsException("非法发送短信渠道!");
	}
    }

}
